package com.bringspring.system.base.util;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.UserProvider;
import com.bringspring.common.util.context.SpringContext;
import com.bringspring.system.permission.entity.OrganizeEntity;
import com.bringspring.system.permission.entity.RoleEntity;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.entity.UserRelationEntity;
import com.bringspring.system.permission.service.OrganizeService;
import com.bringspring.system.permission.service.RoleService;
import com.bringspring.system.permission.service.UserRelationService;
import com.bringspring.system.permission.service.UserService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class UserAuthAreaUtils {


    /**
     * @param userId   用户id
     * @param roleType 角色类型
     * @param scope    授权区域查询访问  1 向下查询（用来我能看到的其他人的数据，比如我授权范围河南，其他人授权返回是河南开封，我就能看到数据），默认，2 向上查询（用来查询）
     *                 谁能看到我的数据，一般来说是查询我的领导，比如我授权返回是河南开封，那么授权是华中河南或者华中的都可以看到我
     * @return
     */
    public static List<String> getHaveSameAuthAreaWithMe(String userId, List<String> roleType, Integer scope) {
        UserProvider userProvider = SpringContext.getBean("userProvider");
        UserRelationService userRelationService = SpringContext.getBean("userRelationServiceImpl");
        UserService userService = SpringContext.getBean("userServiceImpl");
        RoleService roleService = SpringContext.getBean("roleServiceImpl");
        OrganizeService organizeService = SpringContext.getBean("organizeServiceImpl");
        UserEntity info = userService.getInfo(userId);
//        String companyId = info.getCompanyId();
        OrganizeEntity byId = organizeService.getById(info.getOrganizeId());
        String companyId = organizeService.getOrganizeIds(byId);
        List<UserRelationEntity> arealist = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, userId));
        if (CollectionUtil.isEmpty(arealist)) {
            return CollectionUtil.list(false);
        }
        List<String> authAreaIdList = arealist.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
        List<List<String>> address = CollectionUtil.list(false);
        for (String str : authAreaIdList) {
            String[] split = str.replace("\"", "").replace("[", "").replace("]", "").split(",");
            List<String> list = Arrays.asList(split);
            address.add(list);
        }
        if (CollectionUtil.isNotEmpty(address)) {
            address.stream().filter(x -> {
                boolean flag1 = x.size() < 2 && x.get(0).equals("10");
                return !flag1;
            }).collect(Collectors.toList());
            if (address.size() < 2 && address.get(0).equals("10")) {
                return CollectionUtil.list(false);
            }
        }
        //查询本公司的人员ID
//        List<UserEntity> userEntities = userService.getUserListByCompanyId(CollectionUtil.list(false, companyId));
        List<UserEntity> userEntities = userService.getListByOraganizetionId(companyId);

        List<String> userIdList = userEntities.stream().map(UserEntity::getId).collect(Collectors.toList());
        QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(UserRelationEntity::getUserId, userIdList);
//                .in(UserRelationEntity::getObjectId, authAreaIdList);
        if (CollectionUtil.isNotEmpty(address)) {
            queryWrapper.lambda().and((x -> {
                for (List<String> ll : address) {
                    List<String> addressList = JsonUtil.getJsonToList(ll, String.class);
                    if (addressList.size() > 1) {
                        if (scope == null || scope == 1) {
                            String collect = addressList.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(","));
                            collect = "[" + collect;
                            x.or().like(UserRelationEntity::getObjectId, collect);
                        }
                        if (scope != null && scope == 2) {
                            int size = addressList.size();
                            String region = "";
                            String prov = "";
                            String city = "";
                            String area = "";
                            List<String> hh = CollectionUtil.list(false);
                            if (size > 0) {
                                region = addressList.get(0);
                                hh.add(new StringBuffer("[\"" + region + "\"").toString());
                                if (size > 1) {
                                    prov = addressList.get(1);
                                    hh.set(0, hh.get(0) + "]");
                                    hh.add(new StringBuffer("[\"" + region + "\"," + "\"" + prov + "\"").toString());
                                }
                                if (size > 2) {
                                    hh.set(1, hh.get(1) + "]");
                                    city = addressList.get(2);
                                    hh.add(new StringBuffer("[\"" + region + "\"," + "\"" + prov + "\"" + ",\"" + city + "\"").toString());
                                }
                                if (size > 3) {
                                    hh.set(2, hh.get(2) + "]");
                                    area = addressList.get(3);
                                    hh.add(new StringBuffer("[\"" + region + "\"," + "\"" + prov + "\"" + ",\"" + city + "\"" + ",\"" + area + "\"").toString());

                                }

                            }
                            if (CollectionUtil.isNotEmpty(hh)) {
                                hh.set(hh.size() - 1, hh.get(hh.size() - 1) + "]");
                                for (String s : hh) {
                                    x.or().like(UserRelationEntity::getObjectId, s);
                                }
                            }
                        }

                    } else {
                        String s = addressList.get(addressList.size() - 1);
                        s = "[" + "\"" + s + "\"";
                        x.or().like(UserRelationEntity::getObjectId, s);
                    }
                }
            }));
        }
//        String sql = toSql(queryWrapper);
        List<UserRelationEntity> list = userRelationService.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return CollectionUtil.list(false);
        }
        List<String> searchUserIdList = list.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(roleType)) {
            List<String> jiaojiUser = CollectionUtil.list(false);
            for (String str : searchUserIdList) {
                List<RoleEntity> listByUserId = roleService.getListByUserId(str);
                List<String> collect = listByUserId.stream().map(RoleEntity::getType).collect(Collectors.toList());
                List<String> jiaoji = roleType.stream().filter(collect::contains).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(jiaoji)) {
                    jiaojiUser.add(str);
                }
            }
            return jiaojiUser;
        }
        return searchUserIdList;
    }

    /**
     * 获取本公司与当前登录人有相同授权区域的人
     *
     * @return
     */
    public static List<String> getHaveSameAuthAreaWithMe() {
        UserProvider userProvider = SpringContext.getBean("userProvider");
        UserInfo userInfo = userProvider.get();
        return getHaveSameAuthAreaWithMe(userInfo.getUserId(), CollectionUtil.list(false), 1);
    }

    public static List<String> getHaveSameAuthAreaAndRoleTypeWithMe() {
        UserProvider userProvider = SpringContext.getBean("userProvider");
        RoleService roleService = SpringContext.getBean("roleServiceImpl");
        UserInfo userInfo = userProvider.get();
        List<RoleEntity> listByUserId = roleService.getListByUserId(userInfo.getUserId());
        List<String> roleTypes = CollectionUtil.list(false);
        if (CollectionUtil.isNotEmpty(listByUserId)) {
            roleTypes = listByUserId.stream().map(RoleEntity::getType).collect(Collectors.toList());
        }
        return getHaveSameAuthAreaWithMe(userInfo.getUserId(), roleTypes, 1);
    }

    /**
     * @param scope 授权区域查询访问  1 向下查询（用来我能看到的其他人的数据，比如我授权范围河南，其他人授权返回是河南开封，我就能看到数据），默认，2 向上查询（用来查询）
     *              谁能看到我的数据，一般来说是查询我的领导，比如我授权返回是河南开封，那么授权是华中河南或者华中的都可以看到我
     * @return
     */
    public static List<String> getHaveSameAuthAreaAndRoleTypeWithMe(Integer scope) {
        UserProvider userProvider = SpringContext.getBean("userProvider");
        RoleService roleService = SpringContext.getBean("roleServiceImpl");

        UserInfo userInfo = userProvider.get();
        List<RoleEntity> listByUserId = roleService.getListByUserId(userInfo.getUserId());
        List<String> roleTypes = CollectionUtil.list(false);
        if (CollectionUtil.isNotEmpty(listByUserId)) {
            roleTypes = listByUserId.stream().map(RoleEntity::getType).collect(Collectors.toList());
        }
        return getHaveSameAuthAreaWithMe(userInfo.getUserId(), roleTypes, scope);
    }
}
